<template>
    <div>
        <ly-dialog v-model="dialogVisible" :title="loadingTitle" width="70%" top="2%"  :before-close="handleClose" class="form-dialog">
            <el-form :inline="false" :model="formData" :rules="rules" ref="rulesForm" label-position="right" label-width="auto" class="form-data">
                <div class="form-data-item">
                <div class="form-title">基础信息</div>
                        <el-form-item label="班次名称：" prop="name">
                            <el-input v-model.trim="formData.name" placeholder="请输入班次名称" style="width: 300px"></el-input>
                        </el-form-item>
                        <el-form-item label="坐位数：" prop="nums">
                            <el-input-number v-model="formData.nums"  :min="0" :max="9999"></el-input-number>
                        </el-form-item>
                        <el-form-item label="班次状态：" prop="status">
                            <el-radio-group v-model="formData.status" style="width: 380px">
                                <el-radio :label="true">上架</el-radio>
                                <el-radio :label="false">下架</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="发车时间" prop="startlist">
                            <div class="spec-item">
                                <el-tag type="warning" size="large" closable color="primary" v-for="(j, indexn) in startlist" :key="indexn" :name="j" @close="handleRemove(startlist, indexn)">{{ j }}</el-tag>
                                <el-input placeholder="发车时间"  v-model="starttime" style="width: 200px">
                                    <template #append>
                                        <el-button style="color: #FFF;background-color: #409EFF;border-color: #409EFF;" @click="addStartTime(startlist,index)">添加</el-button>
                                    </template>
                                </el-input>
                            </div>
                        </el-form-item>
                    </div>
                <div class="form-data-item">
                    <div class="form-title">站点配置</div>
                        <!-- 多规格-->
                        <div>
                            <el-form-item label="站点配置" prop="startlist">
                                <div class="spec-item">
                                    <el-tag type="warning" size="large" closable color="primary" v-for="(j, indexn) in stationlist" :key="indexn" :name="j" @close="handleRemove(stationlist, indexn)">{{ j }}</el-tag>
                                    <el-input placeholder="站点配置"  v-model="stationname" style="width: 200px">
                                        <template #append>
                                            <el-button style="color: #FFF;background-color: #409EFF;border-color: #409EFF;" @click="addStation(stationlist,index)">添加</el-button>
                                        </template>
                                    </el-input>
                                </div>
                            </el-form-item>
                            <el-form-item  label=""  class="is-required">
                                <el-button  type="success" @click="generateSpec()"  v-if="generatenowBnt" style="margin-left:10px">生成价格</el-button>
                            </el-form-item>
                            <el-form-item  label="" style="padding-right: 10px">
                                <!-- 多规格表格展示设置-->
                                <!-- 批量设置-->
                                <div style="width: 100%">
                                    <!-- 多规格表格-->
                                    <div class="table" v-if="tableColumnList.length>0">
                                        <span>票价：</span>
                                        <el-table :data="tableColumnList" border  style="width: 100%">
                                            <el-table-column prop="start" label="出发站" min-width="150">
                                                <template #default="scope">
                                                  <span>{{ scope.row["start"] }}</span>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="end" label="到达站" min-width="150">
                                                <template #default="scope">
                                                  <span>{{ scope.row["end"] }}</span>
                                                </template>
                                            </el-table-column>

                                            <el-table-column prop="price" label="成人票" min-width="150">
                                                <template #default="scope">
                                                    <el-input-number v-model="scope.row.price" :precision="2" controls-position="right" :min="0" :max="9999999" label="成人票" style="width: 100%"></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="mprice" label="儿童票" min-width="150">
                                                <template #default="scope">
                                                    <el-input-number v-model="scope.row.mprice" :precision="0" controls-position="right" :min="0" :max="9999999" label="儿童票" style="width: 100%"></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="time" label="到达分钟" min-width="150">
                                                <template #default="scope">
                                                    <el-input v-model="scope.row.time" :picker-options="{selectableRange: '00:00:00 - 24:59:59',format:'HH:mm'}"  placeholder="任意时间点"></el-input>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="操作" min-width="100">
                                              <template #default="scope">
                                                  <span class="table-operate-btn" @click="singleSpecDel(scope.$index)" v-if="generatenowBnt">删除</span>
                                                  <span class="table-operate-btn" @click="handleEdit(scope.row)" v-if="!generatenowBnt">保存修改</span>
                                              </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </el-form-item>
                        </div>
                    </div>
            </el-form>
            <template #footer>
                <el-button @click="handleClose" :loading="loadingSave">取消</el-button>
                <el-button type="primary" @click="submitData" :loading="loadingSave">确定</el-button>
            </template>
        </ly-dialog>
    </div>
</template>

<script>
    import TEditor from '@/components/TEditor'
    import vuedraggable from "vuedraggable"
    import {
        mallGoodstype,
        mallGoodsspu,
        mallGoodsspuAdd,
        mallGoodsspuEdit,
        mallGoodsspueEditskups,
        platformsettingsUploadPlatformImg
    } from "@/api/api";
    import LyDialog from "@/components/dialog/dialog";
    import LyUploadGoods from "@/components/upload/goods";
    import {deepClone} from "@/utils/util"
    export default {
        emits: ['refreshData'],
        name: "addModuleGoodsManage",
        components: {
            LyUploadGoods,
            LyDialog,
            TEditor,
            draggable: vuedraggable,
        },
        data() {
            return {
                pics:[],
                starttime:'',
                startlist:[],
                stationlist:[],
                stationname:'',
                generatenowBnt:true,
                tableColumnList:[],//表格展示
                //自定义规格结束
                dialogVisible:false,
                loadingSave:false,
                loadingTitle:'',
                formData:{
                    name: '',
                    nums: 0,
                    times: [],
                    stations: [],
                    prices: [],
                    status: false,
                },
                rules:{
                    name: [
                        {required: true, message: '请输入路线名称',trigger: 'blur'}
                    ],

                }
            }
        },
        mounted() {
            window.addEventListener("focusin", this.onFocusIn,true);
        },
        unmounted() {
            window.removeEventListener("focusin", this.onFocusIn);
        },
        methods:{
            onFocusIn(e){
                e.stopImmediatePropagation()//阻止当前和后面的一系列事件
            },
            addModuleFn(item,flag) {
                this.loadingTitle=flag
                this.dialogVisible=true
                if(item){
                    this.formData = deepClone(item)
                    this.createBnt = false
                    this.generatenowBnt = true
                    this.formData.times.map((item) => {this.startlist.push(item)})
                    this.formData.stations.map((item) => {this.stationlist.push(item)})
                    this.formData.prices.map((item3)=>{
                        this.tableColumnList.push({
                            id: item3.id,
                            start: item3.start,
                            end: item3.end,
                            price: item3.price,
                            mprice: item3.mprice,
                            time: item3.time
                        })
                    })
                }
            },
            handleEdit(row){
                const params = {
                    id:row.id,
                    start: row.start,
                    end: row.end,
                    price:row.price,
                    mprice:row.stock,
                    time: row.time
                }
                this.$confirm('确定要修改保存吗？', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return mallGoodsspueEditskups(params).then(res=>{
                        if(res.code == 2000) {
                            vm.$message.success(res.msg)
                            vm.search()
                        } else {
                            vm.$message.warning(res.msg)
                        }
                    })
                })
            },
            /*
            * 规格方法自定义开始
            * */
            //清空添加的规格和值得缓存
            clearAttr() {
              this.starttime=""
              this.startlist=[]
              this.stationname=""
              this.stationlist=[]
            },
            addStartTime(){
                if (this.starttime!=""){
                    this.startlist.push(this.starttime)
                    this.starttime=""
                }
            },
            addStation(){
                if (this.stationname!=""){
                    this.stationlist.push(this.stationname)
                    this.stationname=""
                }
            },
            // 删除属性
            handleRemove(item, index) {
                item.splice(index, 1);
            },
            // 笛卡尔积算法
            cartesianProductOf(array) {
                if (array.length < 2) return array[0] || []
                var res = []
                array.forEach(function(c,index1) {
                    array.forEach(function(s,index2) {
                        if (index2>index1){
                            var t = [].concat(Array.isArray(c) ? c : [c])
                            t.push(s)
                            res.push(t)
                        }
                    })
                })
                return res
      
            },
            //立即生成规格表
            generateSpec(){
                if(this.stationlist.length<=0){return }
                // 表格内容数据（笛卡尔积算法）
                let finalArr = this.cartesianProductOf(this.stationlist)
                let tableObj = []
                tableObj = finalArr.map((item) => {
                    let obj = {
                        start: item[0],
                        end: item[1],
                        price: 0,
                        mprice: 0,
                        time: 0,
                    }
                    return obj
                })
                this.tableColumnList = tableObj //表格内容数据
            },
            //规格表格展示-删除
            singleSpecDel(index){
                this.$confirm('确定要删除吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(this.tableColumnList.length<=1){
                        this.$message.warning("只有一个不能删除")
                        return
                    }
                    this.tableColumnList.splice(index,1)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                }).catch(() => {
                });
            },
            /*
            * 规格方法自定义结束
            * */
            handleClose() {
                this.dialogVisible=false
                this.loadingSave=false
                this.clearAttr()
                this.formData={
                    name: '',
                    nums:0,
                    times:[],
                    stations:[],
                    prices:[],
                    status:false,
                },
                this.tableColumnList=[]
                this.generatenowBnt=true//立即生成按钮是否显示
                this.$emit('refreshData')
            },
            submitData() {
                this.$refs['rulesForm'].validate(obj=>{
                    if(obj) {
                        let param = {
                            ...this.formData
                        }
                        param.status==param.status?1:0
                        param.times=this.startlist
                        param.stations=this.stationlist
                        param.prices = this.tableColumnList
                        this.loadingSave=true
                        if(this.formData.id){
                            mallGoodsspuEdit(param).then(res=>{
                                this.loadingSave=false
                                if(res.code ==2000) {
                                    this.$message.success(res.msg)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                } else {
                                    this.$message.warning(res.msg)
                                }
                            })
                        }else{
                            let that = this;
                            if(that.tableColumnList.length<1){
                                this.loadingSave=false
                                this.$message.warning("请点击立即生成")
                                return;
                            }
                            mallGoodsspuAdd(param).then(res=>{
                                this.loadingSave=false
                                if(res.code == 2000) {
                                    this.$message.success(res.msg)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                } else {
                                    this.$message.warning(res.msg)
                                }
                            })
                        }
                        this.loadingSave=false
                    }
                })
            },
        },
    }
</script>
<style lang="scss" scoped>
    /*::v-deep(.el-dialog__body) {*/
    /*    padding: 0 30px !important;*/
    /*}*/
    .add-specs-inner{
        padding: 10px;
        background: #fffcfc;
        border: 1px solid #e0e0e0;
        .tips{
            font-size: 12px;
            color: #999999;
        }
        .add-specs-item{
            display: flex;
            align-items: center;
            .name{
                width: 60px;
                font-size: 12px;
            }
        }
    }
    .uploadImg{
        display: flex;
        line-height: 36px;
        font-size: 14px;
        .photoNum{
            font-weight: bold;
            em{
                font-style: normal;
                color: #ff0000;
            }
        }
        .input-fileup{
            width: 120px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            overflow: hidden;
            position: relative;
            background: #409EFF;
            color: #ffffff;
            border: 1px solid #dcdfe6;
            text-decoration: none;
            display: block;
            margin: 0 15px 0 5px;
            border-radius: 3px;
            /*color: #666666;*/
            input{
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                cursor: pointer;
            }
        }
    }

    .pickAlbumPreListO{
        width: 100%;
        background: #f1f1f1;
        /*height: 224px;*/
        .tipsCon{
            text-align: center;
            color: #999999;
        }
    }
    .pickAlbumPreList {
        display: table;
        margin: 0;
        padding: 0;
        /*height: 174px;*/
        li {
            width: 110px;
            padding: 10px;
            box-sizing: border-box;
            /*height: 140px;*/
            display: block;
            float: left;
            margin: 5px;
            position: relative;
            font-size: 12px;
            text-align: center;
            img,.el-image {
                display: block;
                width: 90px;
                height: 90px;
                border: 1px solid #d6d6d6;
            }
            i.el-icon-close{
                display: none;
                position: absolute;
                right: 0;
                top: 0;
                background: #409eff;
                color: #ffffff;
                font-size: 20px;
                cursor: pointer;
            }
            .btnchang{
                display: flex;
                margin-top: 10px;
                align-items: center;
                align-content: center;
            }
            .sizeImg{
                color: #ff0000;
            }
            button{
                width: 40px;
                margin: 0 auto;
                padding: 0;
                height: 28px;
            }
            &:hover i.el-icon-close{
                display: block;
            }
            i.el-icon-picture{
                width: 90px;
                height: 90px;
                display: block;
                text-align: center;
                line-height: 90px;
                border: 1px solid #e1e1e1;
                font-size: 20px;
                border-radius: 4px;
                background: #fff;
            }
        }
    }
    // 规格样式
    .tag-item{
        display: flex;
        flex-direction: row;
        column-gap: 10px;
        background: #f1f1f1;
        padding: 8px;
        margin-bottom: 10px;
        .el-icon-s-grid{
            color: #e6ddd8;
            font-size: 32px;
            cursor: move;
        }
        .input-item{
            flex: 1;
            display: flex;
            flex-direction: column;
            column-gap: 10px;
            .el-icon-error{
                font-size: 14px;
                color: #000000;
                cursor: pointer;
            }
            .spec-item{
                flex: 1;
                display: flex;
                flex-direction: row;
                align-items: center;
                column-gap: 10px;

            }
        }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 128px;
      height: 128px;
      line-height: 128px;
      text-align: center;
    }
    .avatar {
      width: 128px;
      height: 128px;
      display: block;
    }
    .form-data {
        height: calc(100vh - 200px);
        overflow-y: auto;
        border: 1px solid  #b3d8ff;
        .form-title{
            color: #409eff;
            background: #ecf5ff;
            padding: 10px;
            margin-bottom: 20px;
        }
    }
</style>
